package com.hcb.tonguetiphealth.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.model.FileInfo;



public class HttpUtils {
	private static final int MANAGER_TIMEOUT = 1 * 1000;
	private static final int REQUEST_TIMEOUT = 5 * 1000;
	private static final int SO_TIMEOUT = 4 * 1000;
	private static final String CHARSET = HTTP.UTF_8;

	private static final String TAG = "HttpUtils";

	public static HttpClient getHttpClient() {
		HttpParams params = new BasicHttpParams();

		// 设置一些基本参数
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpProtocolParams
				.setUserAgent(
						params,
						"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
								+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

		// 从连接池中取连接的超时时间
		ConnManagerParams.setTimeout(params, MANAGER_TIMEOUT);
		// 连接超时
		HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
		// 请求超时
		HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);

		// 设置我们的HttpClient支持HTTP和HTTPS两种模式
		SchemeRegistry schReg = new SchemeRegistry();
		SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
		sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https", sf, 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);
		return new DefaultHttpClient(conMgr, params);
	}

	public static HttpClient getSSLHttpClient() {

		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new MySecureProtocolSocketFactory(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, registry);

			return new DefaultHttpClient(ccm, params);

		} catch (Exception e) {
			Log.e(TAG, "创建HTTP Client出错：", e);
			// e.printStackTrace();
			return new DefaultHttpClient();
		}

	}

	public static InputStream retriveInputSteam(String requrl) {
		InputStream is = null;
		URL url = null;
		// URLConnection urlconn = null;
		HttpURLConnection conn = null;
		try {
			url = new URL(requrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				is = conn.getInputStream();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return is;
	}
	public static String retriveReplyString(String requrl) {
		HttpClient client = null;
		String str = null;
		client = new DefaultHttpClient();
		HttpPost get = new HttpPost(requrl);
		HttpResponse response;
		try {
			response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				System.err.println(response.getEntity().getContentEncoding());
				str = EntityUtils.toString(response.getEntity());
//				str = new String(str.getBytes("ISO-8859-1"), "UTF-8");  
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return str;
	}
	 
	public static InputStream getInputStream(String url) throws Exception {
		HttpClient client = null;
		InputStream is = null;
		client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			is = response.getEntity().getContent();
		}
		return is;
	}

	/*
	* NameValuePair实现请求参数的封装
	*/
	/*********************************************************************
		List <NameValuePair> params = new ArrayList <NameValuePair>();
	
		params.add(new BasicNameValuePair(strName1, strValue1));
		params.add(new BasicNameValuePair(strName2, strValue2));
		params.add(new BasicNameValuePair(strName3, strValue3));
		params.add(new BasicNameValuePair(strName4, strValue4));
	***********************************************************************/
	public static String Post1(String url, List<NameValuePair> params) {
		String reply = null;
		HttpClient client = null;
		try {
			client = getHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				reply = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			Log.e(TAG, "向" + url + "发出POST请求出错：", e);
		} finally {
			if (null != client) {
				client.getConnectionManager().shutdown();
			}
		}
		return reply;
	}
	
	public static String Post(String url, List<NameValuePair> params) {
		String reply = null;
		for (int i = 0; i < 3; i++) {
			reply = Post1(url, params);
			if (reply !=null)break;
		}
		return reply;
	}

	public static String  PostFile(String url ,List<NameValuePair> params, FileInfo fileInfo) {
		String reply = null;
		HttpClient httpclient= new DefaultHttpClient();
		  HttpPost httpPost= new HttpPost(url);
		     MultipartEntity mulentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
		        for (int i = 0; i < params.size(); i++) {
					String key = params.get(i).getName();
					String value = params.get(i).getValue();
					try {
						mulentity.addPart(key, new StringBody(value, Charset.defaultCharset()));
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} 
		       //添加图片表单数据        
		        if (fileInfo.getUrl() !=null && !fileInfo.getUrl().equals("")) {
		        	File file =  new File(fileInfo.getUrl());
			        FileBody filebody = new FileBody(file); 
			        mulentity.addPart(fileInfo.getName(), filebody);
				}
		        httpPost.setEntity(mulentity);
		        HttpResponse response;
				try {
					response = httpclient.execute(httpPost);
					reply = EntityUtils.toString(response.getEntity());
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        
		        
		return reply;
	}
	
	/**
	 * 
	 * @param url
	 * @param params
	 * @param fileList List<FileInfo>
	 * @return
	 */
	public static String Post(String url, List<NameValuePair> params, List<FileInfo> fileList) {
		String reply = null;
		HttpClient client = null;
		try {
			client =  new DefaultHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
			
			//-------------- 传输文件 ---------------------------------------------------------------
				if(fileList != null && fileList.size() > 0) {
					MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
					File file;
					ContentBody cbFile;
					for(FileInfo fileInfo:fileList) {
						file = new File(fileInfo.getUrl());
						cbFile = new FileBody(file);
						mpEntity.addPart(fileInfo.getName(), cbFile); // <input type="file" name="userfile" /> 对应的
					}
					post.setEntity(mpEntity);
				}
			//-------------- 传输文件 ---------------------------------------------------------------
			
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity he = response.getEntity();
				InputStream is = he.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				StringBuffer sb = new StringBuffer();
				String readLine = null;
				while ((readLine = br.readLine()) != null) {
					//readLine = new String(readLine.getBytes("ISO-8859-1"), "UTF-8");
					sb.append(readLine.trim());
				}
				is.close();
				br.close();
				reply = sb.toString();
				
				/*reply = EntityUtils.toString(response.getEntity());
				reply = new String(reply.getBytes("ISO-8859-1"), "UTF-8");*/
			}
		} catch (Exception e) {
			Log.e(TAG, "向" + url + "发出POST请求出错：", e);
		} finally {
			if (null != client) {
				client.getConnectionManager().shutdown();
			}
		}
		return reply;
	}
	
	
	public static long getContentLength(String url) {
		long len = 0;
		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}
		HttpClient c = getHttpClient();
		HttpGet get = new HttpGet(url + "?random=" + Math.random());   // 加随机数清空缓存
		try {
			HttpResponse response = c.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				len = (entity.getContentLength());
				Log.d(TAG, "获取" + url + "网页大小：" + len);
			}

		} catch (Exception e) {
			Log.e(TAG, "获取" + url + "网页大小出错：", e);
		} finally {
			c.getConnectionManager().shutdown();
		}
		return len;
	}
	public static String doGet(String getUrl) throws ClientProtocolException, IOException, Exception {
		String URL = formatURLAddr(getUrl);
		String response = null;
		
		HttpGet httpGet = new HttpGet(URL);
		//HttpClient hc = new DefaultHttpClient();
		HttpClient hc = getHttpClient();
		HttpResponse ht = hc.execute(httpGet);
		int statusCode = ht.getStatusLine().getStatusCode();
		
		if (statusCode == HttpStatus.SC_OK) {
			response = EntityUtils.toString(ht.getEntity());
			
			/*HttpEntity he = ht.getEntity();
			InputStream is = he.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			
			String readLine = null;
			while ((readLine = br.readLine()) != null) {
				response = response + readLine;
			}
			is.close();
			br.close();*/
		}
		if(null != response && Global.DEBUG) {
			System.out.println("----- doGet: " + response);
		}
		return response;
	}
	
	private static String formatURLAddr(String URL) {
		return URL.replace(" ", "%20"); 
	}
}
